package api

import (
	"KumquatDrivesServices/api/userFileModuleApi"
	"KumquatDrivesServices/api/userModuleApi"
	"KumquatDrivesServices/api/userRecycleModuleApi"
	"KumquatDrivesServices/api/userShareModuleApi"
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/jwts"
	redisjwts "KumquatDrivesServices/service/redis_jwts"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type ApiGruop struct {
	UserModuleApi        userModuleApi.UserModuleApi
	UserFileModuleApi    userFileModuleApi.UserFileModuleApi
	UserRecycleModuleApi userRecycleModuleApi.UserRecycleModuleApi
	UserShareModuleApi   userShareModuleApi.UserShareModuleApi
}

func (ApiGruop) RefreshToken(c *gin.Context) {
	type RefreshTokenRequires struct {
		RefreshToken string `json:"refreshToken" binding:"required"`
		AccessToken  string `json:"accessToken" binding:"required"`
	}
	var refreshTokenRequires RefreshTokenRequires
	if err := c.ShouldBindJSON(&refreshTokenRequires); err != nil {
		logrus.Errorf("param error:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	bol, HasTokenBlackErr := redisjwts.HasTokenBlack(refreshTokenRequires.RefreshToken)
	if HasTokenBlackErr != nil {
		logrus.Errorf("has token black error:%v", HasTokenBlackErr)
		res.FailWithCode(res.INVALID_TOKEN, c)
		return
	}
	if !bol {
		res.FailWithCode(res.INVALID_TOKEN, c)
		return
	}
	accessToken, refreshToken, RefreshTokenErr := jwts.RefreshToken(refreshTokenRequires.AccessToken, refreshTokenRequires.RefreshToken)
	if RefreshTokenErr != nil {
		if errors.Is(RefreshTokenErr, jwts.ErrTokenExpiredMaxRefresh) {
			res.FailWithCode(res.TOKEN_EXPIRED_MAX_REFRESH, c)
			return
		}
		logrus.Errorf("refresh token error:%v", RefreshTokenErr)
		res.FailWithCode(res.INVALID_TOKEN, c)
		return
	}
	res.OkWithData(map[string]string{
		"accessToken":  accessToken,
		"refreshToken": refreshToken,
	}, c)
}

var ApiGruopApp = new(ApiGruop)
